import React, { useState, useEffect } from 'react';
import { DormitoryBuilding, Dormitory, getDormitoryBuildings, addDormitoryBuilding, updateDormitoryBuilding, deleteDormitoryBuilding, getDormitories } from '../mock/dormitoryData';

// 定义表单数据类型
interface BuildingFormData extends Omit<DormitoryBuilding, 'id'> {} 

/**
 * 宿舍楼管理组件
 * 提供宿舍楼信息的增删改查功能
 */
const DormitoryBuildingManagement: React.FC = () => {
  const [buildings, setBuildings] = useState<DormitoryBuilding[]>([]);
  const [dormitories, setDormitories] = useState<Dormitory[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [currentBuilding, setCurrentBuilding] = useState<DormitoryBuilding | null>(null);
  const [selectedBuildingId, setSelectedBuildingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<BuildingFormData>({
    name: '',
    address: '',
  });
  const [loading, setLoading] = useState(true);
  const [dormLoading, setDormLoading] = useState(false);
  const [formErrors, setFormErrors] = useState<Record<string, string>>({});
  
  // 筛选和分页相关状态
  const [filters, setFilters] = useState({
    name: '',
    address: '',
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

    // 获取宿舍楼数据
    const fetchBuildings = async () => {
      setLoading(true);
      try {
        const data = await getDormitoryBuildings();
        setBuildings(data);
      } catch (error) {
        console.error('获取宿舍楼数据失败:', error);
        alert('获取宿舍楼数据失败: ' + (error instanceof Error ? error.message : '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    // 获取宿舍数据
    const fetchDormitories = async (buildingId: number | null) => {
      if (!buildingId) {
        setDormitories([]);
        return;
      }

      setDormLoading(true);
      try {
        const building = buildings.find(b => b.id === buildingId);
        if (!building) {
          setDormitories([]);
          return;
        }

        const allDormitories = await getDormitories();
        // 过滤出当前宿舍楼的宿舍
        const buildingDormitories = allDormitories.filter(dorm => dorm.buildingName === building.name);
        setDormitories(buildingDormitories);
      } catch (error) {
        console.error('获取宿舍数据失败:', error);
        alert('获取宿舍数据失败: ' + (error instanceof Error ? error.message : '未知错误'));
      } finally {
        setDormLoading(false);
      }
    };

    // 处理宿舍楼选择
    const handleBuildingSelect = (buildingId: number) => {
      setSelectedBuildingId(prevId => prevId === buildingId ? null : buildingId);
      fetchDormitories(buildingId === selectedBuildingId ? null : buildingId);
    };

    // 添加宿舍楼
    const addBuildingAction = async (values: BuildingFormData) => {
      try {
        const newBuilding = await addDormitoryBuilding(values);
        setBuildings([...buildings, newBuilding]);
        alert('添加宿舍楼成功');
        return true;
      } catch (error) {
        console.error('添加宿舍楼失败:', error);
        alert('添加宿舍楼失败: ' + (error instanceof Error ? error.message : '未知错误'));
        return false;
      }
    };

    // 更新宿舍楼
    const updateBuildingAction = async (values: BuildingFormData) => {
      if (!currentBuilding) return false;
      
      try {
        const updatedBuilding = await updateDormitoryBuilding(currentBuilding.id, values);
        if (updatedBuilding) {
          const updatedBuildings = buildings.map(building => 
            building.id === currentBuilding.id ? updatedBuilding : building
          );
          setBuildings(updatedBuildings);
          alert('更新宿舍楼成功');
          return true;
        }
        alert('更新宿舍楼失败: 宿舍楼不存在');
        return false;
      } catch (error) {
        console.error('更新宿舍楼失败:', error);
        alert('更新宿舍楼失败: ' + (error instanceof Error ? error.message : '未知错误'));
        return false;
      }
    };

    // 删除宿舍楼
    const deleteBuildingAction = async (id: number) => {
      try {
        const success = await deleteDormitoryBuilding(id);
        if (success) {
          const updatedBuildings = buildings.filter(building => building.id !== id);
          setBuildings(updatedBuildings);
          alert('删除宿舍楼成功');
        } else {
          alert('删除宿舍楼失败: 宿舍楼不存在');
        }
      } catch (error) {
        console.error('删除宿舍楼失败:', error);
        alert('删除宿舍楼失败: ' + (error instanceof Error ? error.message : '未知错误'));
      }
    };

    // 显示添加模态框
    const showAddModal = () => {
      setIsEditMode(false);
      setFormData({
        name: '',
        address: '',
      });
      setFormErrors({});
      setIsModalVisible(true);
    };

    // 显示编辑模态框
    const showEditModal = (building: DormitoryBuilding) => {
      setIsEditMode(true);
      setCurrentBuilding(building);
      setFormData({
        name: building.name,
        address: building.address,
      });
      setFormErrors({});
      setIsModalVisible(true);
    };

    // 处理表单输入变化
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
      const { name, value } = e.target;
      setFormData(prev => ({
        ...prev,
        [name]: value
      }));
    };

    // 验证表单
    const validateForm = () => {
      const errors: Record<string, string> = {};
      
      if (!formData.name.trim()) {
        errors.name = '宿舍楼名称不能为空';
      }
      
      if (!formData.address.trim()) {
        errors.address = '地址不能为空';
      }
      
      setFormErrors(errors);
      return Object.keys(errors).length === 0;
    };

    // 处理表单提交
    const handleSubmit = async (e: React.FormEvent) => {
      e.preventDefault();
      if (validateForm()) {
        const success = isEditMode ? await updateBuildingAction(formData) : await addBuildingAction(formData);
        if (success) {
          setIsModalVisible(false);
        }
      }
    };

    // 处理表单取消
    const handleCancel = () => {
      setIsModalVisible(false);
      setFormErrors({});
    };

    // 组件挂载时获取数据
  useEffect(() => {
    fetchBuildings();
  }, []);
  
  // 重置页码当筛选条件改变时
  useEffect(() => {
    setCurrentPage(1);
  }, [filters]);



  // 处理筛选条件变化
  const handleFilterChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFilters(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 重置筛选条件
  const resetFilters = () => {
    setFilters({
      name: '',
      address: '',
    });
  };
  
  // 筛选和分页后的建筑列表
  const filteredAndPagedBuildings = React.useMemo(() => {
    let filtered = [...buildings];
    
    // 应用筛选条件
    if (filters.name) {
      filtered = filtered.filter(building => 
        building.name.toLowerCase().includes(filters.name.toLowerCase())
      );
    }
    
    if (filters.address) {
      filtered = filtered.filter(building => 
        building.address.toLowerCase().includes(filters.address.toLowerCase())
      );
    }
    
    // 应用分页
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return filtered.slice(startIndex, endIndex);
  }, [buildings, filters, currentPage, pageSize]);
  
  // 总页数
  const totalPages = Math.ceil(buildings.length / pageSize);
  
  // 处理页码变化
  const handlePageChange = (page: number) => {
    if (page > 0 && page <= totalPages) {
      setCurrentPage(page);
    }
  };
  
  // 处理每页数量变化
  const handlePageSizeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const newPageSize = Number(e.target.value);
    setPageSize(newPageSize);
    setCurrentPage(1); // 重置到第一页
  };
  
  // 生成页码按钮
  const renderPageButtons = () => {
    const buttons = [];
    
    // 上一页按钮
    buttons.push(
      <button
        key="prev"
        style={{ ...styles.pageButton, ...(currentPage === 1 ? styles.disabledButton : {}) }}
        onClick={() => handlePageChange(currentPage - 1)}
        disabled={currentPage === 1}
      >
        上一页
      </button>
    );
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
      // 只显示当前页附近的页码和首尾页
      if (i === 1 || i === totalPages || Math.abs(i - currentPage) <= 2) {
        buttons.push(
          <button
            key={i}
            style={{ ...styles.pageButton, ...(i === currentPage ? styles.currentPageButton : {}) }}
            onClick={() => handlePageChange(i)}
          >
            {i}
          </button>
        );
      } else if (i === 2 || i === totalPages - 1) {
        // 添加省略号
        buttons.push(
          <span key={`ellipsis-${i}`} style={styles.pageEllipsis}>...</span>
        );
      }
    }
    
    // 下一页按钮
    buttons.push(
      <button
        key="next"
        style={{ ...styles.pageButton, ...(currentPage === totalPages ? styles.disabledButton : {}) }}
        onClick={() => handlePageChange(currentPage + 1)}
        disabled={currentPage === totalPages}
      >
        下一页
      </button>
    );
    
    return buttons;
  };
  
  return (
    <div style={styles.container}>
      <div style={styles.header}>
        <h2 style={styles.title}>宿舍楼管理</h2>
        <button style={styles.addButton} onClick={showAddModal}>
          添加宿舍楼
        </button>
      </div>
      
      {/* 筛选条件 */}
      <div style={styles.filterContainer}>
        <div style={styles.filterRow}>
          <div style={styles.filterGroup}>
            <label style={styles.filterLabel}>名称:</label>
            <input
              type="text"
              name="name"
              value={filters.name}
              onChange={handleFilterChange}
              style={styles.filterInput}
              placeholder="请输入宿舍楼名称"
            />
          </div>
          
          <div style={styles.filterGroup}>
            <label style={styles.filterLabel}>地址:</label>
            <input
              type="text"
              name="address"
              value={filters.address}
              onChange={handleFilterChange}
              style={styles.filterInput}
              placeholder="请输入宿舍楼地址"
            />
          </div>
          
          <button style={styles.resetButton} onClick={resetFilters}>
            重置筛选
          </button>
        </div>
      </div>
      
      {/* 表格 */}
      <div style={styles.tableContainer}>
        {loading ? (
          <div style={styles.loading}>加载中...</div>
        ) : filteredAndPagedBuildings.length === 0 ? (
          <div style={styles.emptyList}>暂无符合条件的宿舍楼</div>
        ) : (
          <table style={styles.table}>
            <thead style={styles.tableHead}>
              <tr>
                <th style={styles.tableHeader}>名称</th>
                <th style={styles.tableHeader}>地址</th>
                <th style={styles.tableHeader}>查看宿舍</th>
                <th style={styles.tableHeader}>操作</th>
              </tr>
            </thead>
            <tbody>
              {filteredAndPagedBuildings.map(building => (
                <tr key={building.id} style={styles.tableRow}>
                  <td style={styles.tableCell}>{building.name}</td>
                  <td style={styles.tableCell}>{building.address}</td>
                  <td style={styles.tableCell}>
                    <button 
                      style={{ 
                        ...styles.viewButton, 
                        backgroundColor: selectedBuildingId === building.id ? '#722ed1' : '#1890ff'
                      }} 
                      onClick={() => handleBuildingSelect(building.id)}
                    >
                      {selectedBuildingId === building.id ? '收起宿舍' : '查看宿舍'}
                    </button>
                  </td>
                  <td style={styles.tableCell}>
                    <button style={styles.editButton} onClick={() => showEditModal(building)}>
                      编辑
                    </button>
                    <button style={styles.deleteButton} onClick={() => deleteBuildingAction(building.id)}>
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
            </table>
          )}
        </div>
        {!loading && buildings.length > 0 && (
          <div style={styles.paginationContainer}>
            <div style={styles.paginationInfo}>
              显示第 {(currentPage - 1) * pageSize + 1} 至 {Math.min(currentPage * pageSize, buildings.length)} 条，共 {buildings.length} 条
            </div>
            
            <div style={styles.paginationControls}>
              <div style={styles.pageSizeSelectContainer}>
                <label style={styles.pageSizeLabel}>每页显示：</label>
                <select
                  value={pageSize}
                  onChange={handlePageSizeChange}
                  style={styles.pageSizeSelect}
                >
                  <option value={5}>5条</option>
                  <option value={10}>10条</option>
                  <option value={20}>20条</option>
                  <option value={50}>50条</option>
                </select>
              </div>
              
              <div style={styles.pageButtons}>
                {renderPageButtons()}
              </div>
            </div>
          </div>

        )}
      
      {/* 宿舍列表 */}
      {selectedBuildingId && (
        <div style={styles.dormTableContainer}>
          <h3 style={{ marginTop: 0, marginBottom: '16px', fontSize: '18px', color: '#333' }}>
            {buildings.find(b => b.id === selectedBuildingId)?.name} 宿舍列表
          </h3>
          
          {dormLoading ? (
            <div style={styles.dormTableLoading}>加载宿舍数据中...</div>
          ) : dormitories.length > 0 ? (
            <table style={styles.dormTable}>
              <thead>
                <tr>
                  <th style={styles.dormTableHeader}>宿舍号</th>
                  <th style={styles.dormTableHeader}>是否满员</th>
                </tr>
              </thead>
              <tbody>
                {dormitories.map(dorm => (
                  <tr key={dorm.id}>
                    <td style={styles.dormTableCell}>{dorm.roomNumber}</td>
                    <td style={styles.dormTableCell}>
                      {dorm.members.length >= 4 ? (
                        <span style={{ color: '#ff4d4f', fontWeight: 500 }}>是</span>
                      ) : (
                        <span style={{ color: '#52c41a', fontWeight: 500 }}>否</span>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <div style={styles.dormTableEmpty}>该宿舍楼暂无宿舍信息</div>
          )}
        </div>
      )}
      
      {/* 宿舍楼编辑模态框 */}
      {isModalVisible && (
        <div style={styles.modalOverlay}>
          <div style={styles.modal}>
            <div style={styles.modalHeader}>
              <h3 style={styles.modalTitle}>{isEditMode ? '编辑宿舍楼' : '添加宿舍楼'}</h3>
              <button style={styles.closeButton} onClick={handleCancel}>
                ×
              </button>
            </div>
            <div style={styles.modalBody}>
              <form style={styles.form} onSubmit={handleSubmit}>
                <div style={styles.formGroup}>
                  <label style={styles.formLabel} htmlFor="name">名称 *</label>
                  <input
                    id="name"
                    type="text"
                    name="name"
                    value={formData.name}
                    onChange={handleInputChange}
                    style={styles.formInput}
                    placeholder="请输入宿舍楼名称"
                    required
                  />
                  {formErrors.name && <div style={styles.errorText}>{formErrors.name}</div>}
                </div>
                
                <div style={styles.formGroup}>
                  <label style={styles.formLabel} htmlFor="address">地址 *</label>
                  <input
                    id="address"
                    type="text"
                    name="address"
                    value={formData.address}
                    onChange={handleInputChange}
                    style={styles.formInput}
                    placeholder="请输入宿舍楼地址"
                    required
                  />
                  {formErrors.address && <div style={styles.errorText}>{formErrors.address}</div>}
                </div>
                

                
                <div style={styles.formActions}>
                  <button type="button" style={styles.cancelButton} onClick={handleCancel}>
                    取消
                  </button>
                  <button type="submit" style={styles.submitButton}>
                    确定
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 样式定义
const styles: Record<string, React.CSSProperties> = {
  container: {
    padding: '20px',
    fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
  },
  header: {
    marginBottom: '20px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  title: {
    margin: 0,
    fontSize: '24px',
    fontWeight: 600,
    color: '#333',
  },
  addButton: {
    padding: '8px 16px',
    backgroundColor: '#1890ff',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'background-color 0.3s',
  },
  
  // 筛选相关样式
  filterContainer: {
    marginBottom: '20px',
    padding: '16px',
    backgroundColor: '#f5f5f5',
    borderRadius: '4px',
    border: '1px solid #e8e8e8',
  },
  filterRow: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px',
    flexWrap: 'wrap',
  },
  filterGroup: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  filterLabel: {
    fontSize: '14px',
    color: '#333',
    minWidth: '60px',
  },
  filterInput: {
    padding: '6px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
    width: '200px',
  },
  resetButton: {
    padding: '6px 16px',
    backgroundColor: '#fff',
    color: '#666',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  
  // 表格相关样式
  tableContainer: {
    overflowX: 'auto',
    border: '1px solid #e8e8e8',
    borderRadius: '4px',
  },
  loading: {
    padding: '40px',
    textAlign: 'center',
    color: '#999',
  },
  emptyList: {
    padding: '40px',
    textAlign: 'center',
    color: '#999',
  },
  table: {
    width: '100%',
    borderCollapse: 'collapse',
  },
  tableHead: {
    backgroundColor: '#fafafa',
  },
  tableHeader: {
    padding: '12px',
    textAlign: 'left',
    borderBottom: '1px solid #e8e8e8',
    fontWeight: 500,
    fontSize: '14px',
    color: '#333',
  },
  tableRow: {
    transition: 'background-color 0.3s',
  },
  tableCell: {
    padding: '12px',
    borderBottom: '1px solid #e8e8e8',
    fontSize: '14px',
    color: '#333',
  },
  editButton: {
    padding: '4px 8px',
    backgroundColor: '#52c41a',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
    marginRight: '4px',
  },
  deleteButton: {
    padding: '4px 8px',
    backgroundColor: '#ff4d4f',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
  },
  viewButton: {
    padding: '4px 8px',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '12px',
  },
  
  // 分页相关样式
  paginationContainer: {
    marginTop: '20px',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  paginationInfo: {
    fontSize: '14px',
    color: '#666',
  },
  paginationControls: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px',
  },
  pageSizeSelectContainer: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
  },
  pageSizeLabel: {
    fontSize: '14px',
    color: '#666',
  },
  pageSizeSelect: {
    padding: '4px 8px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
  },
  pageButtons: {
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
  },
  pageButton: {
    padding: '4px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    backgroundColor: 'white',
    color: '#666',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'all 0.3s',
  },
  currentPageButton: {
    backgroundColor: '#1890ff',
    color: 'white',
    borderColor: '#1890ff',
  },
  pageEllipsis: {
    padding: '4px 8px',
    color: '#999',
    fontSize: '14px',
  },
  disabledButton: {
    opacity: 0.5,
    cursor: 'not-allowed',
  },
  
  // 宿舍列表相关样式
  dormTableContainer: {
    margin: '20px 0',
    padding: '16px',
    backgroundColor: '#f9f9f9',
    borderRadius: '4px',
    border: '1px solid #e8e8e8',
  },
  dormTable: {
    width: '100%',
    borderCollapse: 'collapse',
  },
  dormTableHeader: {
    padding: '10px',
    textAlign: 'left',
    borderBottom: '1px solid #e8e8e8',
    fontWeight: 500,
    fontSize: '13px',
    color: '#333',
    backgroundColor: '#f0f0f0',
  },
  dormTableCell: {
    padding: '10px',
    borderBottom: '1px solid #e8e8e8',
    fontSize: '13px',
    color: '#333',
  },
  dormTableEmpty: {
    padding: '40px',
    textAlign: 'center',
    color: '#999',
  },
  dormTableLoading: {
    padding: '40px',
    textAlign: 'center',
    color: '#999',
  },
  modalOverlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.45)',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    zIndex: 1000,
  },
  modal: {
    width: '520px',
    backgroundColor: 'white',
    borderRadius: '8px',
    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
  },
  modalHeader: {
    padding: '16px 24px',
    borderBottom: '1px solid #f0f0f0',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  modalTitle: {
    margin: 0,
    fontSize: '16px',
    fontWeight: 500,
    color: '#333',
  },
  closeButton: {
    background: 'none',
    border: 'none',
    fontSize: '20px',
    color: '#999',
    cursor: 'pointer',
    padding: 0,
    width: '24px',
    height: '24px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
  modalBody: {
    padding: '24px',
  },
  form: {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  formGroup: {
    display: 'flex',
    flexDirection: 'column',
    gap: '8px',
  },
  formLabel: {
    fontSize: '14px',
    fontWeight: 500,
    color: '#333',
  },
  formInput: {
    padding: '8px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
    transition: 'border-color 0.3s',
  },
  formSelect: {
    padding: '8px 12px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    fontSize: '14px',
    transition: 'border-color 0.3s',
  },
  errorText: {
    color: '#ff4d4f',
    fontSize: '12px',
    marginTop: '4px',
  },
  formActions: {
    display: 'flex',
    justifyContent: 'flex-end',
    gap: '12px',
    marginTop: '8px',
  },
  cancelButton: {
    padding: '8px 16px',
    backgroundColor: 'white',
    color: '#333',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'all 0.3s',
  },
  submitButton: {
    padding: '8px 16px',
    backgroundColor: '#1890ff',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
    transition: 'background-color 0.3s',
  },
};

export default DormitoryBuildingManagement;